package com.example.web;


import com.example.Util.JwtUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.alibaba.fastjson.JSON;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;


//登录之后  过滤器
@Component
public class LoginedFiler extends ZuulFilter {

    /**
     * filterType：过滤器类型
     * <p>
     * pre：路由之前
     * routing：路由之时
     * post： 路由之后
     * error：发送错误调用
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }


    /**
     * filterOrder：过滤的顺序 序号配置可参照 https://blog.csdn.net/u010963948/article/details/100146656
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }


    /**
     * shouldFilter：判断是否要执行过滤
     *
     * @return true表示需要过滤，将对该请求执行run方法
     */
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String path = context.getRequest().getServletPath();
        if("/user/login".equals(path) || "/user/pwdlogin".equals(path)  ){
            return true;
        }

        return false;
    }



    @Autowired
    StringRedisTemplate redisTemplate;
    /**
     * run：具体过滤的业务逻辑，可做身份验证，校验参数等等
     *
     * @return
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        //获取上游服务返回的结果
        // String body = context.getResponseBody();
        String body ="" ;
        //getResponseDataStream() 一旦获取的上游的响应数据
        //那么该数据就会被截留
        InputStream inputStream = context.getResponseDataStream();
        byte[] bytes = new byte[1024];
        try {
            int count = inputStream.read(bytes);
            body = new String(bytes,0,count);
        } catch (IOException e) {
            throw new RuntimeException("error",e);
        }

        if(body != null){
            //获取用户信息

            Map<String,Object> map = new HashMap<>();
            map.put("userId",body);
            String jwt = JwtUtil.createJWT(30,map);

            redisTemplate.delete("jwt");
            redisTemplate.opsForValue().set("jwt",jwt);
            context.setResponseBody(jwt);
        }
        else{
            //返回原数据
            context.setResponseBody("登录失败!");
        }

        return null;
    }


}
